<template>
	<view class="add-address">
		<!-- 地图区域 -->
		<view class="map-wrapper">
			<map class="map" :latitude="mapCenter.latitude" :longitude="mapCenter.longitude" :markers="markers"
				:scale="16" :show-location="true"></map>
		</view>

		<!-- 表单区域 -->
		<view class="form-wrapper">
			<view class="form-group">
				<!-- 联系人 -->
				<view class="form-item">
					<text class="label">联系人</text>
					<uv-input v-model="form.receiverName" placeholder="请输入收货人姓名" border="none" :customStyle="inputStyle"
						:clearable="true" />
				</view>

				<!-- 手机号码 -->
				<view class="form-item">
					<text class="label">手机号码</text>
					<uv-input v-model="form.receiverPhone" placeholder="请输入收货人手机号" type="number" :maxlength="11"
						border="none" :customStyle="inputStyle" :clearable="true" />
				</view>

				<!-- 所在地区 -->
				<view class="form-item location-item" @tap="chooseLocation">
					<text class="label">收货地址</text>
					<view class="location-wrapper">
						<view v-if="form.detailAddress" class="location-info">
							<text
								class="address">{{form.detailAddress}}</text>
							<text class="tip">点击重新选择</text>
						</view>
						<view v-else class="placeholder-wrapper">
							<uv-icon name="map" size="32" color="#666"></uv-icon>
							<text class="placeholder">点击选择收货地址</text>
						</view>
						<uv-icon name="arrow-right" size="32" color="#c8c9cc"></uv-icon>
					</view>
				</view>

				<!-- 详细地址输入框 -->
				<view class="form-item">
					<text class="label">详细地址</text>
					<view class="textarea-wrapper">
						<uv-textarea v-model="form.addressDetail" placeholder="请输入详细地址，如楼层、门牌号等" :maxlength="50"
							:customStyle="textareaStyle" autoHeight />
						<text class="word-count">{{form.addressDetail.length}}/50</text>
					</view>
				</view>
			</view>

			<!-- 设为默认 -->
			<view class="form-group">
				<view class="switch-item">
					<text class="label">设为默认地址</text>
					<switch :checked="form.isDefault" @change="onSwitchChange" color="#3c9cff" />
				</view>
			</view>
		</view>

		<!-- 底部按钮 -->
		<view class="action-bar">
			<button class="submit-btn" @tap="submitForm">
				保存
			</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				id: null,
				form: {
					receiverName: '',
					receiverPhone: '',
					detailAddress: '',
					addressDetail: '',
					isDefault: false,
					latitude: null,
					longitude: null
				},
				// 地图中心点
				mapCenter: {
					latitude: 39.909,
					longitude: 116.397
				},
				// 地图标记点
				markers: [],
				inputStyle: {
					padding: '0',
					height: '44rpx',
					backgroundColor: '#ffffff'
				},
				textareaStyle: {
					padding: '0',
					backgroundColor: '#ffffff',
					height: '120rpx'
				}
			}
		},

		computed: {
			isFormValid() {
				return this.form.receiverName &&
					this.form.receiverPhone &&
					this.form.province &&
					this.form.detailAddress &&
					this.form.addressDetail
			},

			// 判断是否是编辑模式
			isEdit() {
				return !!this.id
			}
		},

		onLoad(options) {
			if (options.id) {
				this.id = options.id
				this.loadAddressDetail()
			} else {
				// 获取当前位置作为初始位置
				this.getCurrentLocation()
			}
		},

		methods: {
			// 获取当前位置
			getCurrentLocation() {
				uni.getLocation({
					type: 'gcj02',
					success: (res) => {
						this.updateMapCenter(res.latitude, res.longitude)
					},
					fail: () => {
						uni.showToast({
							title: '获取位置失败',
							icon: 'none'
						})
					}
				})
			},

			// 更新地图中心点和标记
			updateMapCenter(latitude, longitude) {
				this.mapCenter = {
					latitude,
					longitude
				}
				this.markers = [{
					id: 1,
					latitude,
					longitude,
					width: 32,
					height: 32
				}]
			},

			// 加载地址详情
			async loadAddressDetail() {
				try {
					const data = await this.$http.get(`/address/${this.id}`)
					if (data) {
						this.form = {
							id: data.id,
							receiverName: data.receiverName,
							receiverPhone: data.receiverPhone,
							province: data.province,
							city: data.city,
							district: data.district,
							street: data.street,
							detailAddress: data.detailAddress,
							addressDetail: data.addressDetail,
							isDefault: data.isDefault,
							latitude: data.latitude,
							longitude: data.longitude
						}

						// 如果有经纬度信息，更新地图中心点
						if (data.latitude && data.longitude) {
							this.updateMapCenter(data.latitude, data.longitude)
						} else {
							// 如果没有经纬度信息，获取当前位置
							this.getCurrentLocation()
						}
					}
				} catch (e) {
					console.error('获取地址详情失败:', e)
					uni.showToast({
						title: '获取地址详情失败',
						icon: 'none'
					})
				}
			},

			// 选择地址
			chooseLocation() {
				uni.chooseLocation({
					success: (res) => {
						console.log('选择的地址', res);
						// 更新地图中心点
						this.updateMapCenter(res.latitude, res.longitude)
						// 保存详细地址和经纬度
						this.form.detailAddress = res.address + res.name
						this.form.latitude = res.latitude
						this.form.longitude = res.longitude
					},
					fail: (err) => {
						console.error('选择位置失败：', err)
						if (err.errMsg.includes('auth deny')) {
							uni.showModal({
								title: '提示',
								content: '需要您授权位置权限',
								success: (res) => {
									if (res.confirm) {
										uni.openSetting()
									}
								}
							})
						}
					}
				})
			},

			// 切换默认地址
			onSwitchChange(e) {
				this.form.isDefault = e.detail.value
			},

			// 提交表单
			async submitForm() {
				// 表单验证
				if (!this.form.receiverName) {
					return uni.showToast({
						title: '请输入联系人',
						icon: 'none'
					})
				}

				if (!this.form.receiverPhone) {
					return uni.showToast({
						title: '请输入手机号码',
						icon: 'none'
					})
				}

				// 验证手机号格式
				if (!/^1[3-9]\d{9}$/.test(this.form.receiverPhone)) {
					return uni.showToast({
						title: '手机号格式不正确',
						icon: 'none'
					})
				}

				if (!this.form.detailAddress) {
					return uni.showToast({
						title: '请选择地址',
						icon: 'none'
					})
				}

				if (!this.form.addressDetail) {
					return uni.showToast({
						title: '请输入详细地址',
						icon: 'none'
					})
				}

				try {
					const url = this.isEdit ? `/address/update` : '/address/add'
					const data = await this.$http.post(url, this.form)

					if (data) {
						uni.showToast({
							title: this.isEdit ? '修改成功' : '添加成功',
							icon: 'none'
						})

						// 返回上一页并刷新列表
						setTimeout(() => {
							const pages = getCurrentPages()
							const prevPage = pages[pages.length - 2]
							if (prevPage) {
								prevPage.$vm.loadAddressList()
							}
							uni.navigateBack()
						}, 1500)
					}
				} catch (e) {
					console.error(this.isEdit ? '修改地址失败:' : '添加地址失败:', e)
					uni.showToast({
						title: this.isEdit ? '修改失败' : '添加失败',
						icon: 'none'
					})
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import 'add_address.scss';
</style>